package fair.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import fair.constant.MessageConstant;
import fair.entity.Result;
import fair.service.MemberService;
import fair.service.ReportService;
import fair.service.SetMealService;
import fair.utils.DateUtils;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fair_wu
 * @version v1.0
 * @package fair.controller
 * @date 2021-02-08 下午 22:14
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;


    @GetMapping("/exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try {
            /*Map<String, Object> result = new HashMap<>();
            getBusinessMap(result);*/
            Map<String, Object> result = reportService.getBusinessReportData();
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business.jasper";
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));
            OutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出运营数据Excel
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
/*            Map<String, Object> result = new HashMap<>();
            getBusinessMap(result);*/
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //在内存中创建一个excel表格对象
            String path = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(path)));
            XSSFSheet sheet = excel.getSheetAt(0);
            //第三行第六列
            XSSFRow xssfRow = sheet.getRow(2);
            xssfRow.getCell(5).setCellValue(reportDate);
            //第五行
            xssfRow = sheet.getRow(4);
            xssfRow.getCell(5).setCellValue(todayNewMember);
            xssfRow.getCell(7).setCellValue(totalMember);
            //第六行
            xssfRow = sheet.getRow(5);
            xssfRow.getCell(5).setCellValue(thisWeekNewMember);
            xssfRow.getCell(7).setCellValue(thisMonthNewMember);
            //第八行
            xssfRow = sheet.getRow(7);
            xssfRow.getCell(5).setCellValue(todayOrderNumber);
            xssfRow.getCell(7).setCellValue(todayVisitsNumber);
            //第九行
            xssfRow = sheet.getRow(8);
            xssfRow.getCell(5).setCellValue(thisWeekOrderNumber);
            xssfRow.getCell(7).setCellValue(thisWeekVisitsNumber);
            //第十行
            xssfRow = sheet.getRow(9);
            xssfRow.getCell(5).setCellValue(thisMonthOrderNumber);
            xssfRow.getCell(7).setCellValue(thisMonthVisitsNumber);
           // 热门套餐
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                xssfRow = sheet.getRow(rowNum++);
                xssfRow.getCell(4).setCellValue((String) map.get("name"));
                xssfRow.getCell(5).setCellValue((Long) map.get("setmeal_count"));
                xssfRow.getCell(6).setCellValue(proportion.doubleValue());
            }
            //通过输出流进行文件下载,基于浏览器进行客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取运营统计表格
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    private void getBusinessMap(Map<String, Object> map) {
        map.put("reportDate", "2021.02.01");
        map.put("todayNewMember", 50);
        map.put("totalMember", 80505);
        map.put("thisWeekNewMember", 110);
        map.put("thisMonthNewMember", 3510);
        map.put("todayOrderNumber", 150);
        map.put("todayVisitsNumber", 140);
        map.put("thisWeekOrderNumber", 540);
        map.put("thisWeekVisitsNumber", 520);
        map.put("thisMonthOrderNumber", 2058);
        map.put("thisMonthVisitsNumber", 2021);

        List<Map<String, Object>> hotSetmeal = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "入职无忧体检套餐（男女通用）");
        map1.put("setmeal_count", 561);
        map1.put("proportion", 0.48);
        hotSetmeal.add(map1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐");
        map2.put("setmeal_count", 328);
        map2.put("proportion", 0.32);
        hotSetmeal.add(map2);
        map.put("hotSetmeal", hotSetmeal);
    }

    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            Map<String, Object> map = getSetmealMap();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    private Map<String, Object> getSetmealMap() {
        Map<String, Object> map = new HashMap<>();
        List<String> setmealNames = new ArrayList<>();
        setmealNames.add("入职无忧体检套餐（男女通用）");
        setmealNames.add("粉红珍爱(女)升级TM12项筛查体检套餐");
        setmealNames.add("阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐");
        setmealNames.add("珍爱高端升级肿瘤12项筛查（男女单人）");
        map.put("setmealNames",setmealNames);

        List<Map<String, Object>> setmealCount = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("value", 1054);
        map1.put("name", "入职无忧体检套餐（男女通用）");

        Map<String, Object> map2 = new HashMap<>();
        map2.put("value", 425);
        map2.put("name", "粉红珍爱(女)升级TM12项筛查体检套餐");

        Map<String, Object> map3 = new HashMap<>();
        map3.put("value", 781);
        map3.put("name", "阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐");

        Map<String, Object> map4 = new HashMap<>();
        map4.put("value", 862);
        map4.put("name", "珍爱高端升级肿瘤12项筛查（男女单人）");

        setmealCount.add(map1);
        setmealCount.add(map2);
        setmealCount.add(map3);
        setmealCount.add(map4);
        map.put("setmealCount",setmealCount);
        return map;
    }

    private Map<String, Object> getSetmealMapDatabase() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = setMealService.findSetmealCount();
        List<String> setmealNames = new ArrayList<>();
        map.put("setmealCount",list);
        for (Map<String, Object> setmeals : list) {
            String name = (String) setmeals.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames",setmealNames);
        return map;
    }

    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            Map<String, Object> map = getMemberMap();
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    private Map<String, Object> getMemberMap() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        months.add("2020.6");
        months.add("2020.7");
        months.add("2020.8");
        months.add("2020.9");
        months.add("2020.10");
        months.add("2020.11");
        months.add("2020.12");
        map.put("months", months);

        List<Integer> memberCount = new ArrayList<>();
        memberCount.add(120);
        memberCount.add(150);
        memberCount.add(180);
        memberCount.add(200);
        memberCount.add(230);
        memberCount.add(270);
        memberCount.add(288);
        map.put("memberCount", memberCount);
        return map;
    }

    private Map<String, Object> getMemberMapDataBase() {
        Map<String, Object> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        List<String> months = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            System.out.println(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        map.put("months", months);
        List<Integer> memberCount = memberService.findMemberCountByMouth(months);
        map.put("memberCount", memberCount);
        return map;
    }
}
